package com.ml.shs.service;

import com.ml.shs.entity.User;
import com.ml.shs.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    @Autowired
    public UserRepository userRepository;

    public User login(User user) throws Exception {
        User userDb = userRepository.findByAccount(user.getAccount());

        if (userDb != null) {
            if (!userDb.getPassword().equals(user.getPassword())) {
                throw new Exception("密码错误");
            }
            return userDb;
        } else {
            user.setRole("common");
            user = userRepository.save(user);
            return user;
        }
    }

    public Optional<User> getInfo(String userId) {
        if (userId != null) {
            return userRepository.findById(userId);
        }
        return null;
    }

    public void update(User user, String userId) throws Exception {
        if (userId != null) {
            Optional<User> optionalUser = userRepository.findById(userId);
            User userDb = optionalUser.get();
            userDb.setContact(user.getContact());
            userDb.setDepartment(user.getDepartment());
            userDb.setNickName(user.getNickName());
            userRepository.save(userDb);
        } else {
            throw new Exception("用户更新异常，没有userId");
        }
    }
}
